package server.servlet;

import server.util.FileUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
/*
静态资源处理器,负责读取静态资源文件的内容发送给客户端,找不到文件则返回404
*/
/*
2023/3/23 该类内容全部写完,后续直接使用,无需修改
by cyl
 */
public class StaticResourcesProcessor implements Servlet {
    private static String webPath = System.getProperty("user.dir") + File.separator + "webapps" + File.separator;;
    private static String[] welcomeFileList = null;

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String uri = response.encodeUrl(request.getRequestURI());;
        int index = uri.indexOf('/', 1);
        String message = "";
        if (index >= 0)
            message = uri.substring(index);
        else
            message = "";

        //处理欢迎文件
        if ("".equals(message) || "/".equals(message)) {
            if (welcomeFileList != null) {
                for (String s : welcomeFileList) {
                    File file = getFile(uri + File.separator + s);
                    if (!file.exists() || !file.isFile()) {
                        continue;
                    }
                    FileUtil.sendData(file, response.getOutputStream());
                    return;
                }
            }
            response.setStatus(HttpServletResponse.SC_NOT_FOUND, message);
            return;
        }

        File file = getFile(uri);
        if (!file.exists() || !file.isFile()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND, message);
            return;
        }
        FileUtil.sendData(file, response.getOutputStream());
    }

    private File getFile(String uri) {
        File file = new File(webPath, uri);
        return file;
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        String welcomeFileCount = servletConfig.getInitParameter("welcomeFileCount");
        if (welcomeFileCount == null)
            return;
        int n = 0;
        try {
            n = Integer.parseInt(welcomeFileCount);
        } catch (Throwable t) {
            n = 0;
        }
        welcomeFileList = new String[n];
        for (int i = 0; i < n; i++) {
            welcomeFileList[i] = servletConfig.getInitParameter("welcomeFile" + i);
        }
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
    }
}
